import router from './router'
import store from './store'
import {toast, tokenCookie, nprogressLoading} from "@/composables/utils.js"

const {getToken} = tokenCookie()
const {startLoading, hideLoading} = nprogressLoading()

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
    startLoading()
    const token = getToken()
    if (!token && to.path !== '/login') {
        return next('/login')
    }
    // 不能重复登录
    if (to.path === '/login' && token) {
        toast('不能重复登录', 'error')
        return next({path: from.path ? from.path : '/home'})
    }
    // 加载用户信息
    if (token) {
        await store.dispatch('getUserInfo')
    }
    next();
    // 页面元信息的设置

    document.title = (to.meta.title ? to.meta.title : "") + "-帝沙商城后台"
});

// 全局后置守卫

router.afterEach((to, path) => hideLoading());

export default router;